package com.ruijie.acl.service;

import java.util.Collection;
import java.util.HashSet;

import org.springframework.util.Assert;

import com.ruijie.batch.plan.BatchPlan;
import com.ruijie.batch.plan.PlanDefinitionRequest;
import com.ruijie.batch.plan.internal.DefaultItemsPlanDefinitionService;
import com.ruijie.batch.plan.items.ExtendPlanDefinitionRequest;
import com.ruijie.batch.plan.items.ExtendPlanDefinitionService;
import com.ruijie.batch.plan.items.ItemParameterService;
import com.ruijie.batch.plan.items.ItemParameters;

public class AclDefaultExtendPlanDefinitionService extends DefaultItemsPlanDefinitionService implements ExtendPlanDefinitionService {
	
	private ItemParameterService itemParameterService;
    
    @SuppressWarnings("unchecked")
    public void populateExtendDefinitionRequest(ExtendPlanDefinitionRequest request) {
        Assert.notNull( request ) ;
        Assert.hasText( request.getSessionCode());
        BatchPlan plan = null;
        if( request.getModifiedId() != null ){
            plan = new BatchPlan();
            plan.setId(request.getModifiedId());
        }
        Collection itemParameters =  getItemParameterService().resolveItemParameterses(plan, request.getSessionCode());
        ((ExtendPlanDefinitionRequest)request).setItemParameters(itemParameters);
    }
    
    @Override
    protected void saveOrUpdatePlanItems(BatchPlan plan, PlanDefinitionRequest request){
        super.saveOrUpdatePlanItems(plan, request);
        if(request instanceof ExtendPlanDefinitionRequest){
            Collection<ItemParameters> itemParameters = new HashSet<ItemParameters>();
            for (Object entry : ((ExtendPlanDefinitionRequest)request).getItemParameters()) {
                itemParameters.add((ItemParameters) ((Object[]) entry)[1]);
            }
            getItemParameterService().updateItemParameterses(plan, itemParameters);
        }
    }
    
    @SuppressWarnings("unchecked")
    public Collection<BatchPlan> findbyItemParameter(String key, String value){
        Assert.hasText(key);
        Assert.hasText(value);
        String hql = "select distinct parameters.plan from ItemParameters as parameters where parameters.parameters[:name] = :value ";
        Collection<BatchPlan> plans = this.createQuery(hql).setParameter("name", key).setParameter("value", value).list();
        return plans;
    }

    public ItemParameterService getItemParameterService() {
        return itemParameterService;
    }

    public void setItemParameterService(ItemParameterService itemParameterService) {
        this.itemParameterService = itemParameterService;
    }

    
}
